package com.rxnetwork.transferee;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.rxnetwork.R;
import com.rxnetwork.transferee.glideloader.GlideImageLoader;
import com.rxnetwork.transferee.tilibrary.style.index.NumberIndexIndicator;
import com.rxnetwork.transferee.tilibrary.style.progress.ProgressBarIndicator;
import com.rxnetwork.transferee.tilibrary.style.progress.ProgressPieIndicator;
import com.rxnetwork.transferee.tilibrary.transfer.TransferConfig;
import com.rxnetwork.transferee.tilibrary.transfer.Transferee;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiaocode on 2017/7/17.
 */

public class TransfereeUtil {
    private static final int WRITE_EXTERNAL_STORAGE = 101;

    private volatile static TransfereeUtil instance;

    private TransfereeUtil() {
    }

    public static TransfereeUtil getInstance() {
        if (instance == null) {
            synchronized (TransfereeUtil.class) {
                if (instance == null) {
                    instance = new TransfereeUtil();
                }
            }
        }
        return instance;
    }

    private Transferee getDefault(Context context) {
        return Transferee.getDefault(context);
    }

    private TransferConfig getConfig(Context context, List<String> sourceImageList) {
        return TransferConfig.build()
                .setSourceImageList(sourceImageList)
                .setMissPlaceHolder(R.mipmap.ic_empty_photo)
                .setProgressIndicator(new ProgressPieIndicator())
                .setImageLoader(GlideImageLoader.with(context))
                .setOnLongClcikListener(new Transferee.OnTransfereeLongClickListener() {
                    @Override
                    public void onLongClick(ImageView imageView, int pos) {
                        saveImageByGlide(imageView);
                    }
                })
                .create();
    }

    private TransferConfig getLocalConfig(Context context, List<String> sourceImageList) {
        return TransferConfig.build()
                .setSourceImageList(sourceImageList)
                .setMissPlaceHolder(R.mipmap.ic_empty_photo)
                .setErrorPlaceHolder(R.mipmap.ic_empty_photo)
                .setProgressIndicator(new ProgressBarIndicator())
                .setIndexIndicator(new NumberIndexIndicator())
                .setJustLoadHitImage(true)
                .setImageLoader(GlideImageLoader.with(context))
                .create();
    }

    private TransferConfig getConfig(Context context, List<ImageView> imageViewList, List<String> imageStrList) {
        return TransferConfig.build()
                .setImageLoader(GlideImageLoader.with(context))
                .setMissPlaceHolder(R.mipmap.ic_empty_photo)
                .setOriginImageList(imageViewList)
                .setSourceImageList(imageStrList)
                .setProgressIndicator(new ProgressBarIndicator())
                .setJustLoadHitImage(true)
                .setOnLongClcikListener(new Transferee.OnTransfereeLongClickListener() {
                    @Override
                    public void onLongClick(ImageView imageView, int pos) {
                        saveImageByGlide(imageView);
                    }
                })
                .create();
    }

    /**
     * 使用 Glide 作为图片加载器时，保存图片到相册使用的方法
     *
     * @param imageView
     */
    private void saveImageByGlide(ImageView imageView) {
        if (checkWriteStoragePermission(imageView.getContext())) {
            GlideBitmapDrawable bmpDrawable = (GlideBitmapDrawable) imageView.getDrawable();
            MediaStore.Images.Media.insertImage(
                    imageView.getContext().getContentResolver(),
                    bmpDrawable.getBitmap(),
                    String.valueOf(System.currentTimeMillis()),
                    "");
            Toast.makeText(imageView.getContext(), "save success", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean checkWriteStoragePermission(Context context) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) context, new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_EXTERNAL_STORAGE);
            return false;
        }
        return true;
    }

    public void displayGlideImg(ImageView imageView, Object item) {
        Glide.with(imageView.getContext())
                .load(item)
                .centerCrop()
                .placeholder(R.mipmap.ic_empty_photo)
                .into(imageView);
    }

    /**
     * 缩放图片浏览
     *
     * @param viewGroup       GridView图片容器
     * @param sourceImageList
     * @param position
     */
    public void onClickShow(ViewGroup viewGroup, List<String> sourceImageList, int position) {
        TransferConfig config = getConfig(viewGroup.getContext(), sourceImageList);
        config.setNowThumbnailIndex(position);
        config.setOriginImageList(wrapOriginImageViewList(viewGroup, sourceImageList.size()));

        getDefault(viewGroup.getContext()).apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
            @Override
            public void onShow() {
                //Glide.with(mContext).pauseRequests();
            }

            @Override
            public void onDismiss() {
//                Glide.with(mContext).resumeRequests();
            }
        });
    }

    /**
     * 本地缩放图片浏览
     *
     * @param viewGroup       GridView图片容器
     * @param sourceImageList
     * @param position
     */
    public void onClickShowLocal(ViewGroup viewGroup, List<String> sourceImageList, int position) {
        TransferConfig config = getLocalConfig(viewGroup.getContext(), sourceImageList);
        config.setNowThumbnailIndex(position);
        config.setOriginImageList(wrapOriginImageViewList(viewGroup, sourceImageList.size()));

        getDefault(viewGroup.getContext()).apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
            @Override
            public void onShow() {
                //Glide.with(mContext).pauseRequests();
            }

            @Override
            public void onDismiss() {
//                Glide.with(mContext).resumeRequests();
            }
        });
    }

    /**
     * @param view
     * @param imageViewList
     * @param imageStrList
     */
    public void onClickShow(View view, List<ImageView> imageViewList, List<String> imageStrList) {
        TransferConfig config = getConfig(view.getContext(), imageViewList, imageStrList);
        config.setNowThumbnailIndex(imageViewList.indexOf(view));
        getDefault(view.getContext()).apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
            @Override
            public void onShow() {
//                Glide.with(mContext).pauseRequests();
            }

            @Override
            public void onDismiss() {
//                Glide.with(mContext).resumeRequests();
            }
        });
    }

    /**
     * @param imageView
     * @param imagePath
     */
    public void onClickShow(ImageView imageView, String imagePath) {
        List<ImageView> imageViewList = new ArrayList<>();
        imageViewList.add(imageView);
        List<String> imageStrList = new ArrayList<>();
        imageStrList.add(imagePath);
        TransferConfig config = getConfig(imageView.getContext(), imageViewList, imageStrList);
        config.setNowThumbnailIndex(imageViewList.indexOf(imageView));
        getDefault(imageView.getContext()).apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
            @Override
            public void onShow() {
//                Glide.with(mContext).pauseRequests();
            }

            @Override
            public void onDismiss() {
//                Glide.with(mContext).resumeRequests();
            }
        });
    }

    /**
     * 包装缩略图 ImageView 集合
     * <p>
     * 注意：此方法只是为了收集 Activity 列表中所有可见 ImageView 好传递给 transferee。
     * 如果你添加了一些图片路径，扩展了列表图片个数，让列表超出屏幕，导致一些 ImageViwe 不
     * 可见，那么有可能这个方法会报错。这种情况，可以自己根据实际情况，来设置 transferee 的
     * originImageList 属性值
     *
     * @return
     */
    @NonNull
    private List<ImageView> wrapOriginImageViewList(ViewGroup viewGroup, int size) {
        List<ImageView> originImgList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            try {
                ImageView thumImg = (ImageView) ((ViewGroup) viewGroup.getChildAt(i)).getChildAt(0);
                originImgList.add(thumImg);
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }
        return originImgList;
    }

    /**
     * 清除glide下载的缓存
     *
     * @param context
     */
    public void clear(Context context) {
        Transferee.clear(GlideImageLoader.with(context));
    }
}
